<template>
  <div class="panel-acount">
    <el-form
      label-width="70px"
      size="large"
      ref="accountRef"
      :model="account"
      :rules="rules"
      status-icon
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" type="password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ElForm, FormInstance, FormRules } from 'element-plus'
// 引入消息提示的反馈类型的组件
import { ElMessage } from 'element-plus'
import useLoginAccountStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cahe'

const loginAccountStore = useLoginAccountStore()

// 定义account 数据 双向绑定到表单中
const account = reactive<IAccount>({
  // localCache.getCache 为了方便在记住密码后的取值
  name: localCache.getCache('name') ?? 'coderwhy',
  password: localCache.getCache('password') ?? '123456'
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '必须输入帐号信息~', trigger: 'blur' },
    { min: 6, max: 15, message: '必须是6~15数字或字母组成~', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '必须输入密码信息~', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,}$/, message: '必须是3位以上数字或字母组成', trigger: 'blur' }
  ]
})

// 校验账号密码是否符合规则，符合才能登录，要先获取整个 from 表单
const accountRef = ref<FormInstance>()
// const accountRef = ref<InstanceType<typeof ElForm>>()

// 执行账号登录逻辑
function loginAction(isRememberPwd: boolean) {
  accountRef.value?.validate((valid) => {
    if (valid) {
      // 获取账号和密码，存入 store 中
      const name = account.name
      const password = account.password

      // 向服务器发送网络请求(携带账号和密码)
      loginAccountStore.loginAccountAction({ name, password }).then((res) => {
        // 登录成功后判断是否要记住密码
        // 父组件传过来判断的参数
        if (isRememberPwd) {
          localCache.setCache('name', name)
          localCache.setCache('password', password)
        }
      })
    } else {
      ElMessage({ showClose: true, message: '登入失败', type: 'error' })
    }
  })
}
// 将函数暴露给 父组件
defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.panel-acount {
  .el-form-item--large {
    --font-size: 15px;
    --el-form-label-font-size: var(--font-size);
  }
}
</style>
